//
//  OrderForTable.m
//  ServiceApp
//
//  Created by User-23 on 12/10/14.
//  Copyright (c) 2014 TrainingCamp. All rights reserved.
//

#import "OrderForTable.h"
#import "OrderDetailForTable.h"
#import "TablesManager.h"
#import "BillsManager.h"

@interface OrderForTable ()

@property (weak, nonatomic) IBOutlet UILabel *totalLabel;
@property Table* selectedTable;
@property NSTimer *updateTimer;

@end

static NSString *kPayBillUrl = @"http://78.90.20.186:8080/ProjectRestaurant/payBill";

@implementation OrderForTable

- (void)viewDidLoad {
    [super viewDidLoad];
    self.updateTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(update) userInfo:nil repeats:YES];

    self.navigationController.navigationBar.hidden = NO;
    
    [[[[self.tabBarController tabBar]items]objectAtIndex:0]setEnabled:NO];
    
    //Get currently selected table
    self.selectedTable = [[TablesManager sharedTables] selectedTable];
    
    //Change Title of View
    self.title = [NSString stringWithFormat:@"Table #%ld", (long)self.selectedTable.tableNumber];
    self.hidesBottomBarWhenPushed = NO;

}



- (void) update{
    [BillsManager getBillForTable:self.selectedTable];
    dispatch_async(dispatch_get_main_queue(), ^{
        self.totalLabel.text = [NSString stringWithFormat:@"Total: %.2f lv.", self.selectedTable.bill.totalBill];
    });
    
}

-(IBAction)payBillButton:(id)sender{
    
    
    NSNumber *billId = [NSNumber numberWithInteger:self.selectedTable.bill.billId];
    NSDictionary *dict = [[NSDictionary alloc] initWithObjectsAndKeys:billId, @"billId", nil];
    if ([NSJSONSerialization isValidJSONObject:dict]) {
        
        NSError *error = nil;
        NSData *result = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
        
        if (error == nil && result != nil) {
            NSData *response = [self jsonPostRequest:result];
            
            NSError* mistake = nil;
            NSDictionary* jsonDictionary = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableLeaves error:&mistake];
            NSString *responseString = jsonDictionary[@"response"];
            if (mistake != nil) {
                NSLog(@"Error : %@", [mistake localizedDescription]);
            }
            else {
                dispatch_async(dispatch_get_main_queue(), ^{
                    UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"Pay Bill" message:responseString delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
                    [alert show];
                    if ([responseString isEqualToString:@"OK"]) {
                        [self.navigationController popViewControllerAnimated:YES];                    }
                    
                });
                
            }
        }
    }
}

-(id) jsonPostRequest:(NSData*) jsonRequestData{
    NSURL *url = [NSURL URLWithString:kPayBillUrl];
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:0 timeoutInterval:60];
    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setValue:[NSString stringWithFormat:@"%lu", (unsigned long)[jsonRequestData length]] forHTTPHeaderField:@"Content-Length"];
    [request setHTTPBody:jsonRequestData];
    
    //send synch request
    NSURLResponse *response = nil;
    NSError *error = nil;
    NSData *result = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
    
    
    if (error == nil) {
        return result;
    }
    else{
        return nil;
    }
}



- (IBAction)detailButton:(id)sender {
    [self performSegueWithIdentifier:@"OrderToDetail" sender:self];
}


@end
